Sys.setlocale("LC_CTYPE", "en_US.UTF-8")
data=read.csv("D:\\北航课程资料\\管理统计学-小组作业\\all_in_one3.csv",header=T)
data$home_win <- ifelse(data$home_win == "True", 1, 0)
c(dim(data),sum(data$home_win),mean(data$home_win))

#用球队属性建立逻辑回归模型
model.team=glm(home_win ~ home_buildUpPlaySpeed+home_buildUpPlayPassing+home_chanceCreationPassing+home_chanceCreationCrossing+home_chanceCreationShooting+home_defencePressure+home_defenceAggression+home_defenceTeamWidth+away_buildUpPlaySpeed+away_buildUpPlayPassing+away_chanceCreationPassing+away_chanceCreationCrossing+away_chanceCreationShooting+away_defencePressure+away_defenceAggression+away_defenceTeamWidth,family=binomial(link=logit),data=data)
summary(model.team)

##卡方检验
1-pchisq(306,df=16)

c(AIC(model.team),BIC(model.team))

model.aic=step(model.team,trace = F)
summary(model.aic)

ss=length(data[,1])
model.bic=step(model.team,trace = F,k=log(ss))
summary(model.bic)

library(pROC)
pred.team=predict(model.team,data)
pred.aic=predict(model.aic,data)
pred.bic=predict(model.bic,data)
Y=data$home_win
roc.team=roc(Y,pred.team)
roc.aic=roc(Y,pred.aic)
roc.bic=roc(Y,pred.bic)
c(roc.team$auc,roc.aic$auc,roc.bic$auc)


par(mfrow=c(1,3))
plot(roc.team,main="全模型")
plot(roc.aic,main="AIC模型")
plot(roc.bic,main="BIC模型")

nsimu=100
p=0.8
ss0=round(ss*p)
AUC=as.data.frame(matrix(0,nsimu,3))
names(AUC)=c("全模型","AIC模型","BIC模型")
for(i in 1:nsimu){
  aa=data[order(runif(ss)),]
  A0=aa[c(1:ss0),]
  A1=aa[-c(1:ss0),]
  
  model.1=glm(home_win ~ home_buildUpPlaySpeed+home_buildUpPlayPassing+home_chanceCreationPassing+home_chanceCreationCrossing+home_chanceCreationShooting+home_defencePressure+home_defenceAggression+home_defenceTeamWidth+away_buildUpPlaySpeed+away_buildUpPlayPassing+away_chanceCreationPassing+away_chanceCreationCrossing+away_chanceCreationShooting+away_defencePressure+away_defenceAggression+away_defenceTeamWidth,family=binomial(link=logit),data=A0)
  model.2=glm(home_win ~ home_buildUpPlayPassing+home_chanceCreationPassing+home_chanceCreationCrossing+home_chanceCreationShooting+home_defencePressure+home_defenceAggression+away_buildUpPlayPassing+away_chanceCreationPassing+away_chanceCreationCrossing+away_defencePressure+away_defenceAggression,family=binomial(link=logit),data=A0)
  model.3=glm(home_win ~ home_buildUpPlayPassing+home_chanceCreationShooting+home_defencePressure+away_buildUpPlayPassing+away_chanceCreationCrossing+away_defencePressure,family=binomial(link=logit),data=A0)
  
  pred.1=predict(model.1,A1)
  pred.2=predict(model.2,A1)
  pred.3=predict(model.3,A1)
  
  Y=A1$home_win
  auc.1=roc(Y,pred.1)$auc
  auc.2=roc(Y,pred.2)$auc
  auc.3=roc(Y,pred.3)$auc
  
  AUC[i,]=c(auc.1,auc.2,auc.3)
}

par(mfrow=c(1,1))
boxplot(AUC,main="外样本AUC对比")

##对随机样本做预测
newdata=read.csv("D:\\北航课程资料\\管理统计学-小组作业\\预测样本.csv",header=T)

probabilities <- predict(model.2, newdata = newdata, type = "response")

# 将概率转换为类别标签，这里使用0.5作为阈值
predicted_classes <- ifelse(probabilities > 0.5, 1, 0)

# 打印预测结果
print(predicted_classes)



